<?php

class Ead_EnviarlinksController extends Ead_Controller_Action
{

    private $_table     = 'LINKUTEIS';
    private $_pk        = 'LNK_ID';
    private $_order_col = 'LNK_ORD';
    private $_order     = 'ASC';
    private $_sta_col   = 'LNK_STA';
    private $obj        = '';
    private $form       = '';
    public  $dir        = 'public/upload/linkuteis/';
    public  $_file_col  = 'LNK_FILE';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Linkuteisead();
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('elemform','library');
        
        $where = $this->_pk.' > 0';
       
        $itfiltro = $this->_getParam('itfiltro', ''); 
        if($itfiltro != '') $where .= ' AND LNK_URL like "' . $itfiltro.'%"';
        $this->view->itfiltro = $itfiltro; 
        
        $where .= ' AND USU_ID = '.Zend_Auth::getInstance()->getStorage()->read()->USU_ID;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    
    public function editAction() {
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('imagem','library');
         Zend_Loader::loadClass('tools','library');
         
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    $id = (int) $formData[$this->_pk]; //$this->form->getValue($this->_pk);
                    
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $formData;//$this->form->getValues();
                    //print_r($data);
                    unset($data['Salvar']);
                    unset($data['MAX_FILE_SIZE']);
                    
                    if(strpos($data['LNK_URL'],'http://') === FALSE) $data['LNK_URL'] = 'http://'.$data['LNK_URL'];
                    
                    if ($id == 0){
                        $data['USU_ID'] = Zend_Auth::getInstance()->getStorage()->read()->USU_ID;
                        $data[$this->_order_col] = tools::returnOrdMax($this->_table, $this->_order_col);
                        $this->db->insert($this->_table,$data);
                        $id = $this->db->lastInsertId();
                        imagem::rename($id,$this->dir,$returnImg['filenew']);
                    }else{                      
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                        $img = glob($this->dir.$id.'.*');
                        foreach($img as $filetemp) $filename = $filetemp;
                        imagem::reizeFull($filename,$filename, '240', '100');

                        $ext = end(explode('.', $filename));
                        imagem::reizeFull($filename,$this->dir.$id.'_hom.'.$ext, '320', '100'); 
                        
                    }
                    
                    $this->_helper->redirector('index');      
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);   
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $data = array($this->_sta_col => 0);
            //$ok = (bool) $this->db->update($this->_table,$data, $this->_pk .' = ' . $id);
            $ok = (bool) $this->db->delete($this->_table,$this->_pk .' = ' . $id);
            
            foreach (glob($this->dir.$id.'_*.*') as $file) {
                unlink($file);
            }
            Zend_Loader::loadClass('imagem','library');
            imagem::delete($id,$this->dir,TRUE);
            
        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function orderAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $sessao = new Zend_Session_Namespace('Professor');
        
        $id = $this->_getParam('id', 0);
        $ord = $this->_getParam('ord', 0);
        $pos = $this->_getParam('pos', 0);
        
        if($id > 0 && $pos == 0)
        {
            
            $query = 'SELECT SQL_CACHE '.$this->_pk.', '.$this->_order_col.' FROM '.$this->_table
                .' WHERE '.$this->_sta_col.' = 1 '
                .' AND '.$this->_order_col.' < '.$ord 
                .' ORDER BY '.$this->_order_col.' DESC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array($this->_order_col => $ord);
                $this->db->update($this->_table,$data, $this->_pk.' = '.$row[$this->_pk] );
                $ord = $row[$this->_order_col];
            }
            
            $data= array($this->_order_col => $ord );
            $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
            
        } else if($id > 0 && $pos == 1) {
            
            $query = 'SELECT SQL_CACHE '.$this->_pk.', '.$this->_order_col.' FROM '.$this->_table
                .' WHERE '.$this->_sta_col.' = 1 '
                .' AND '.$this->_order_col.' > '.$ord 
                .' ORDER BY '.$this->_order_col.' ASC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array($this->_order_col => $ord);
                $this->db->update($this->_table,$data, $this->_pk.' = '.$row[$this->_pk] );
                $ord = $row[$this->_order_col];
            }
            
            $data= array($this->_order_col => $ord );
            $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);   
        }
        
        $this->_helper->redirector('index'); 
    }
}